from typing import List
from fastapi import Depends, HTTPException
from sqlalchemy.orm import Session
import schemas.provincecity_Pydantic
from apis.oauth import oauth_api
from db import engine
from db.session import get_session
from db.session import SessionLocal
from crud.change_province import *

# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# 加入新省份
@oauth_api.post("/createprovince/", response_model = schemas.provincecity_Pydantic.ProvincialCreate)
async def create_province(province: schemas.provincecity_Pydantic.ProvincialCreate, db: Session = Depends(get_db())):


    # 先判断是否省份已经存在
    result = IfExistProvince(province.name)
    if result:
        raise HTTPException(status_code = 404, detail = "没有重名省份，可以添加")

    # 加入新省份
    province_name = CreateProvince(db, newProvince = province.name)


    if province_name:
        raise HTTPException(status_code = 400, detail = "新省份已加入")
    return CreateProvince(db = db, newProvince = province)

# 查询总的省份信息
@oauth_api.get("/getprovince/", response_model = List[schemas.provincecity_Pydantic.GetProvincial])
async def get_province_name():
    result = Getprovince()
    return result

